package main

import (
	"context"
	"fmt"
	"github.com/apache/thrift/lib/go/thrift"
	"phonebook/thrift/gen-go/thrift/generated"
)

// 具体的服务结构，需要实现UserService接口
type ThriftServiceImpl struct {
}

func (t *ThriftServiceImpl) GetUserByUsername(ctx context.Context, username generated.String) (*generated.User, error) {
	fmt.Println("GetUserByUsername from client:" + username)
	friendUser := &generated.User{generated.LongPtr(1), generated.StringPtr(username), generated.BooleanPtr(false), generated.IntPtr(20), nil, nil, nil}
	user := &generated.User{generated.LongPtr(0), generated.StringPtr("tom"), generated.BooleanPtr(true), generated.IntPtr(30), []*generated.User{friendUser}, []generated.String{generated.String("192.168.0.1")}, map[generated.String]*generated.User{"friend": friendUser}}
	return user, nil

}
func (t *ThriftServiceImpl) SaveUser(ctx context.Context, user *generated.User) error {

	fmt.Println("SaveUser from client:" + user.String())
	return &generated.DataException{generated.IntPtr(-1), generated.StringPtr("user has registed"), nil}
}
func main() {
	// TCompactProtocol 压缩二进制
	protocolFactory := thrift.NewTCompactProtocolFactory()
	// transportFactory
	transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
	transport, err := thrift.NewTServerSocket(":8899")
	if err != nil {
		panic(err)
	}

	handler := &ThriftServiceImpl{}
	// 具体的实现，需要实现UserService的接口
	processor := generated.NewUserServiceProcessor(handler)
	sever := thrift.NewTSimpleServer4(processor, transport, transportFactory, protocolFactory)

	if err := sever.Serve(); err != nil {
		panic(err)
	}

}
